package com.funtonow.jqdk.fkcs.ui;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.funtonow.jqdk.R;
import com.funtonow.jqdk.adapter.LoanListAdapter;
import com.funtonow.jqdk.adapter.RepaymentAdapter;
import com.funtonow.jqdk.base.BaseActivity;
import com.funtonow.jqdk.base.BaseBean;
import com.funtonow.jqdk.base.Constants;
import com.funtonow.jqdk.base.SqjAppliaction;
import com.funtonow.jqdk.base.UrlUtils;
import com.funtonow.jqdk.bean.DkNumBean;
import com.funtonow.jqdk.bean.GameThirdInfoListBean;
import com.funtonow.jqdk.bean.LoanInfoBean;
import com.funtonow.jqdk.bean.RepaymentBean;
import com.funtonow.jqdk.bean.UserInfoBean;
import com.funtonow.jqdk.ui.MainActivity;
import com.funtonow.jqdk.ui.VipActivity;
import com.funtonow.jqdk.utils.HttpUtil;
import com.funtonow.jqdk.utils.SPUtil;
import com.funtonow.jqdk.utils.StatisticsUtils;
import com.funtonow.jqdk.utils.ToastUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;

import static com.funtonow.jqdk.base.UrlUtils.APPLY_SQTX;
import static com.funtonow.jqdk.base.UrlUtils.TUI_JIAN;
import static com.funtonow.jqdk.base.UrlUtils.TX;

/**
 * @author Jiajien
 * @date 2019/6/26
 * 审核成功
 */
public class DkSuccessActivity extends BaseActivity implements View.OnClickListener, BaseQuickAdapter.OnItemClickListener {

    @BindView(R.id.rlv_recommend)
    RecyclerView rlvRecommend;
    @BindView(R.id.ll_recommend)
    LinearLayout llRecommend;
    @BindView(R.id.ll_ssq)
    LinearLayout llSsq;
    @BindView(R.id.ll_dk_success)
    LinearLayout llDkSuccess;
    @BindView(R.id.tv_recommend_title)
    TextView tvRecommendTitle;
    @BindView(R.id.tv_loan_money_num)
    TextView tvLoanMoneyNum;
    @BindView(R.id.tv_loan_lv)
    TextView tvLoanLv;
    @BindView(R.id.tv_loan_money_num1)
    TextView tvLoanMpnryNum1;
    @BindView(R.id.tv_contract_num)
    TextView tvContractNum;
    @BindView(R.id.tv_arrival_num)
    TextView tvArriavlNum;
    @BindView(R.id.tv_dk_date)
    TextView tvDkDatae;
    @BindView(R.id.tv_lx_num)
    TextView tvLxNum;
    @BindView(R.id.rlv_repayment)
    RecyclerView rlvRepayment;
    @BindView(R.id.tv_user_agreement)
    TextView tvUserAgreement;

    private LoanListAdapter recommendAdapter;
    private List<GameThirdInfoListBean> gameThirdInfoListBeans = new ArrayList<>();
    private DkNumBean dkNumBean;
    private RepaymentAdapter repaymentAdapter;
    private List<RepaymentBean> repaymentBeans = new ArrayList<>();


    @Override
    public int getLayoutRes() {
        return R.layout.activity_fk_success;
    }

    @Override
    public void onCreateActivity(@Nullable Bundle savedInstanceState) {
        initToolbar(getResources().getString(R.string.title_user_info));
        setAgreement();
        tvRecommendTitle.setText("额度不够？");
        initRecyclerView(rlvRecommend);
        recommendAdapter = new LoanListAdapter();
        rlvRecommend.setAdapter(recommendAdapter);
        initRecyclerView(rlvRepayment);
        repaymentAdapter = new RepaymentAdapter();
        rlvRepayment.setAdapter(repaymentAdapter);
        getAppId();
        recommendAdapter.setOnItemClickListener(this);
        dkNumBean = JSON.parseObject(getIntent().getStringExtra("dkInfo"), DkNumBean.class);
        tvLoanMoneyNum.setText(String.format(Locale.getDefault(), "%d.00", dkNumBean.getKtxed()));
        tvLoanLv.setText(String.format(Locale.getDefault(), "月费率%d%%，期限%d月", dkNumBean.getFlv(), dkNumBean.getQx()));
        tvLoanMpnryNum1.setText(String.format(Locale.getDefault(), "最高可提现额度（元）：%d.00", dkNumBean.getKtxed()));
        tvContractNum.setText(String.format(Locale.getDefault(), "合同金额（元）：%s.00", dkNumBean.getHtje()));
        tvArriavlNum.setText(String.format(Locale.getDefault(), "预计到账金额（元）：%s.00", dkNumBean.getSjdkje()));
        tvDkDatae.setText(String.format(Locale.getDefault(), "贷款期限（月）：%s.00", dkNumBean.getQx()));
        tvLxNum.setText(String.format(Locale.getDefault(), "总息费（元）：%s.00", dkNumBean.getZxf()));
        if (dkNumBean.getState() == 1) {
            llSsq.setVisibility(View.VISIBLE);
            llDkSuccess.setVisibility(View.GONE);
        } else if (dkNumBean.getState() == 2) {
            llDkSuccess.setVisibility(View.VISIBLE);
            llSsq.setVisibility(View.GONE);
            applyTx();
        }
    }

    private void initRecyclerView(RecyclerView recyclerView) {
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        //设置布局管理器
        recyclerView.setLayoutManager(layoutManager);
        //设置为垂直布局，这也是默认的
        layoutManager.setOrientation(RecyclerView.VERTICAL);
        //设置增加或删除条目的动画
        recyclerView.setItemAnimator(new DefaultItemAnimator());

    }

    /**
     * 推荐列表
     */
    private void recommend() {
        UserInfoBean userInfoBean = SPUtil.getUserInfo();
        Map<String, String> param = new HashMap<>();
        assert userInfoBean != null;
        param.put("appid", Constants.OWN_APP_ID);
        param.put("token", userInfoBean.getToken());
        param.put("openid", userInfoBean.getOpenid());
        param.put("showappid", Constants.DATA_APP_ID);
        HttpUtil.getInstance().postDataAsynToNet(TUI_JIAN, param, new HttpUtil.MyNetCall() {
            @Override
            public void success(Call call, String jsonString) throws IOException {
                if (JSON.parseObject(jsonString).getInteger("errnum") != -1) {
                    JSONObject jsonObject = JSON.parseObject(SqjAppliaction.loanInfoBean.getCpMap());
                    String jsonArray = JSON.parseObject(jsonString).getJSONArray("data").toJSONString();
                    List<String> stringList = JSON.parseArray(jsonArray, String.class);
                    for (String s : stringList) {
                        for (LoanInfoBean.HeziInfoListBean heziInfoListBean : SqjAppliaction.loanInfoBean.getHeziInfoList()) {
                            if (s.equals(heziInfoListBean.getGdid())) {
                                for (LoanInfoBean.GdlistBean gdlistBean : SqjAppliaction.loanInfoBean.getGdlist()) {
                                    if (s.equals(gdlistBean.getGdid())) {
                                        GameThirdInfoListBean gameThirdInfoListBean = JSON.parseObject(jsonObject.getJSONObject(gdlistBean.getChanpinid()).toJSONString(), GameThirdInfoListBean.class);
                                        gameThirdInfoListBean.setVipfw(gdlistBean.getVipfw());
                                        gameThirdInfoListBean.setUrl(gdlistBean.getUrl());
                                        gameThirdInfoListBean.setHeziId(heziInfoListBean.getType());
                                        gameThirdInfoListBean.setIndex(heziInfoListBean.getInde());
                                        gameThirdInfoListBean.setGdId(s);
                                        gameThirdInfoListBeans.add(gameThirdInfoListBean);
                                    }
                                }
                            }
                        }
                    }
                    if (gameThirdInfoListBeans.size() > 0) {
                        llRecommend.setVisibility(View.VISIBLE);
                        recommendAdapter.setNewData(gameThirdInfoListBeans);
                    } else {
                        llRecommend.setVisibility(View.GONE);
                    }
                    StatisticsUtils.baoGuang(Constants.HEZI_ID_25);
                }
            }

            @Override
            public void failed(Call call, IOException e) {

            }
        });
    }


    @OnClick({R.id.btn_loan_tx, R.id.btn_agree_xy})
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_loan_tx:
                applyTx();
                llDkSuccess.setVisibility(View.VISIBLE);
                llSsq.setVisibility(View.GONE);
                break;
            case R.id.btn_agree_xy:
                agreeXyAndTx();
                break;
            default:
                break;
        }
    }

    /**
     * 获取数据appId
     */
    private void getAppId() {
        HttpUtil.getInstance().getDataAsynFromNet(UrlUtils.GET_APPID, new HttpUtil.MyNetCall() {
            @Override
            public void success(Call call, String jsonString) throws IOException {
                Constants.DATA_APP_ID = JSON.parseObject(jsonString).getString("appId");
                recommend();
            }

            @Override
            public void failed(Call call, IOException e) {

            }
        });
    }

    /**
     * listView  监听
     *
     * @param adapter
     * @param view
     * @param position
     */
    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        if (SPUtil.getUserInfo() != null && recommendAdapter.getItem(position).getVipfw() == 1
                && SPUtil.getUserInfo().getHasVip() == 0) {
            ToastUtils.show("该产品仅限会员申请");
            startActivity(new Intent(DkSuccessActivity.this, VipActivity.class));
        } else {
            GameThirdInfoListBean gameThirdInfoListBean = recommendAdapter.getItem(position);
            assert gameThirdInfoListBean != null;
            StatisticsUtils.clickUrl(gameThirdInfoListBean);
            StatisticsUtils.intentWebView(DkSuccessActivity.this,
                    gameThirdInfoListBean.getUrl(), gameThirdInfoListBean.getName(),
                    gameThirdInfoListBean.getChanpinid());
        }
        finish();
    }


    /**
     * 申请提现
     */
    private void applyTx() {
        UserInfoBean userInfoBean = SPUtil.getUserInfo();
        Map<String, String> param = new HashMap<>();
        assert userInfoBean != null;
        param.put("appid", Constants.OWN_APP_ID);
        param.put("token", userInfoBean.getToken());
        param.put("openid", userInfoBean.getOpenid());
        param.put("orderid", dkNumBean.getOrderid());
        HttpUtil.getInstance().postDataAsynToNet(APPLY_SQTX, param, new HttpUtil.MyNetCall() {
            @Override
            public void success(Call call, String jsonString) throws IOException {
                BaseBean baseBean = JSON.parseObject(jsonString, BaseBean.class);
                if (baseBean.errnum >= 0) {
                    RepaymentBean repaymentBean = new RepaymentBean();
                    repaymentBean.setTime("还款日");
                    repaymentBean.setHuankuane("还款额");
                    repaymentBean.setBenjin("本金");
                    repaymentBean.setXifei("息费");
                    repaymentBeans.add(repaymentBean);
                    repaymentBeans.addAll(JSON.parseArray(baseBean.data, RepaymentBean.class));
                }
                repaymentAdapter.setNewData(repaymentBeans);
            }

            @Override
            public void failed(Call call, IOException e) {

            }
        });
    }

    private void agreeXyAndTx() {
        UserInfoBean userInfoBean = SPUtil.getUserInfo();
        Map<String, String> param = new HashMap<>();
        assert userInfoBean != null;
        param.put("appid", Constants.OWN_APP_ID);
        param.put("token", userInfoBean.getToken());
        param.put("openid", userInfoBean.getOpenid());
        param.put("orderid", dkNumBean.getOrderid());
        HttpUtil.getInstance().postDataAsynToNet(TX, param, new HttpUtil.MyNetCall() {
            @Override
            public void success(Call call, String jsonString) throws IOException {
                BaseBean baseBean = JSON.parseObject(jsonString, BaseBean.class);
                Intent intent = new Intent(DkSuccessActivity.this, MainActivity.class);
                intent.putExtra("isDkSuccess", true);
                startActivity(intent);
            }

            @Override
            public void failed(Call call, IOException e) {

            }
        });
    }


    /**
     * 设置用户协议
     */
    public void setAgreement() {
        SpannableStringBuilder spannable;
        String content;

        content = "登录即同意《现金贷借款人告知书》《双方-个人消费贷款合同范本》";
        spannable = new SpannableStringBuilder(content);
        spannable.setSpan(new ClickableSpan() {
            @Override
            public void onClick(@NonNull View widget) {
                StatisticsUtils.intentWebView(DkSuccessActivity.this,
                        Constants.SSQ_XJD_HTML, getResources().getString(R.string.xys), "");
            }

            @Override
            public void updateDrawState(@NonNull TextPaint ds) {
                ds.setUnderlineText(false);
            }

        }, 5, 16, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        spannable.setSpan(new ClickableSpan() {
            @Override
            public void onClick(@NonNull View widget) {
                StatisticsUtils.intentWebView(DkSuccessActivity.this,
                        Constants.SSQ_HT_HTML, getResources().getString(R.string.yss), "");
            }

            @Override
            public void updateDrawState(@NonNull TextPaint ds) {
                ds.setUnderlineText(false);
            }

        }, 16, content.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        ForegroundColorSpan span1 = new ForegroundColorSpan(getResources().getColor(R.color.color_4E77FF));
        ForegroundColorSpan span3 = new ForegroundColorSpan(getResources().getColor(R.color.color_4E77FF));
        spannable.setSpan(span1, 5, 14, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        spannable.setSpan(span3, 14, content.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

        tvUserAgreement.setHighlightColor(Color.TRANSPARENT);//去掉点击后的背景颜色为透明
        tvUserAgreement.setMovementMethod(LinkMovementMethod.getInstance());
        tvUserAgreement.setText(spannable);
    }


}
